package utils;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Transaction {

    // connection data
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String JDBC_URL = "jdbc:mysql://localhost:3306/squizme";
    static final String USER = "default_user";
    static final String PWD = "mecatronicapoliusp";
    // connection instance
    private Connection connection = null;

    static {
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Transaction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Transaction() throws Exception {
        connection = DriverManager.getConnection(JDBC_URL, USER, PWD);
        connection.setAutoCommit(false);
    } // begin

    public void commit() throws SQLException {
        try {
            connection.commit();
        } finally {
            connection.close();
        }
    } // commit

    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException ex) {
            Logger.getLogger(Transaction.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(Transaction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } // rollback

    public Connection getConnection() {
        return connection;
    } // getConnection
} // Transaction